package cn.mrcode.fd.blog.listener;

import cn.mrcode.fd.blog.buutil.BeanUtil;
import cn.mrcode.fd.blog.cache.CacheSVUtil;
import cn.mrcode.fd.blog.task.StatHzCleanTask;
import cn.mrcode.fd.blog.task.StatTask;
import cn.mrcode.fd.blog.task.TaskSVUtil;
import cn.mrcode.fd.utils.log.track.LogTrackTemplateUtil;
import cn.mrcode.fd.utils.log.track.LogTrackUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 项目启动后的初始化监听器
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2016/1/1 12:18
 */
public class InitListener implements ServletContextListener{
    private Logger log = LoggerFactory.getLogger(InitListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String apiName = "[项目启动完成后初始化工作]";
        LogTrackUtil.start();
        log.info(LogTrackTemplateUtil.svStart(apiName));
        log.info(LogTrackTemplateUtil.svMsg(apiName,"获取spring bean 容器"));
        //获取不到spring容器则抛出异常，下面的不抛出异常，返回null
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
        //WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        BeanUtil.beans = webApplicationContext;

        //缓存初始化
        CacheSVUtil.refreshCache();

        log.info(LogTrackTemplateUtil.svMsg(apiName, "启动task"));
        TaskSVUtil.startTask();

        log.info(LogTrackTemplateUtil.svEnd(apiName));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        StatHzCleanTask.clean(StatTask.hz);
        LogTrackUtil.end();
    }
}
